package com.example.datasource;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

/**
 * 数据源配置类
 */
public class DataSourceConfig {
    private static final String JDBC_URL = "jdbc:postgresql://localhost:5432/app_db";
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "123456";
    
    private static HikariDataSource dataSource;
    
    /**
     * 创建并配置数据源
     */
    public static synchronized DataSource createDataSource() {
        if (dataSource == null || dataSource.isClosed()) {
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(JDBC_URL);
            config.setUsername(USERNAME);
            config.setPassword(PASSWORD);
            config.setDriverClassName("org.postgresql.Driver");
            
            // 连接池配置
            config.setMaximumPoolSize(10);
            config.setMinimumIdle(2);
            config.setConnectionTimeout(30000);
            config.setIdleTimeout(600000);
            config.setMaxLifetime(1800000);
            config.setLeakDetectionThreshold(60000);
            
            // 连接测试
            config.setConnectionTestQuery("SELECT 1");
            
            dataSource = new HikariDataSource(config);
        }
        return dataSource;
    }
    
    /**
     * 关闭数据源
     */
    public static synchronized void closeDataSource() {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
        }
    }
}
